import { login as _login, request, showToast } from '../../utils/util.js';
import { AuthLoginByWeixin, AuthCode2Session, LoginWxByAccount } from '../../config/api.js';
var app = getApp();
var random = Math.random();

/**
 * 调用微信登录
 */
function loginByWeixin() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return _login().then((res) => {
      code = res.code;
      request(AuthLoginByWeixin, { wx_code: code}, 'POST').then(res => {
        if (res.code === 200) {
          //存储用户信息
          wx.setStorageSync('userInfo', res.data.userInfo);
          wx.setStorageSync('token', res.data.token); 
        }
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

// /**
//  * 获取wx session
//  */
function code2Session() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return _login().then((res) => {
      code = res.code;
      wx.setStorageSync('code', code);
      //登录远程服务器
      request(AuthCode2Session, { wx_code: code }, 'POST').then(res => {
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}


Page({

    /**
     * 页面的初始数据
     */
    data: {
        isAgree:true,
        openid: '',
        wxSessionKey: '',
        account_text: '',
        password_text: '',
        passwordLength:0
    },
    focusPassword(){
        if(this.data.passwordLength == 0 ){
            this.setData({
                passwordLength:-1
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		let that = this;
		if (options.goto_index!=undefined){
			that.setData({
				goto_index: options.goto_index,
			})
		}
		that.setData({
			navH: app.globalData.navHeight,
		});
		that.refreshSessionKey();
    },
	refreshSessionKey() {
		let that = this;
		let code = null;
		_login().then((res) => {
			code = res.code;
			wx.setStorageSync('code', code);
			//登录远程服务器
			return new Promise(function (resolve, reject) {
				request(AuthCode2Session, { wx_code: code }, 'POST').then(res => {
					// console.log(res);
					if (res.code === 1) {
						that.setData({
							wxSessionKey: res.data.session_key,
							openid: res.data.openid,
						});
					}
				}).catch((err) => {
					reject(err);
				});
			})
		});
	},

//-------------微信授权登录（正式）
	//获取code值
	login() {
		var that = this;
		return new Promise(function (resolve, vpay) {
			wx.login({
				success: function (res) {
					if (res.code) {
						//登录远程服务器
						that.setData({
							code: res.code
						})
						resolve(res);
					} else {
						// vpay(res);
					}
				},
				fail: function (err) {
					vpay(err);
				},
			});
		}).catch(function () {
		});
	},

    //-------------账号密码登录（正式）
	account(e) {
		this.setData({
			account_text: e.detail.value
		})
	},
	password(e) {   
		var inputValue = e.detail.value;
		if(this.data.isPassword === 'text'){
			this.setData({
	    		isPassword:'password'
	    	})
		};
		this.setData({
		    password_text: e.detail.value
		})
	},
	is_fill() {
		let that = this;
		if (that.data.account_text == '') {
			wx.showToast({
				title: '请输入账号！',
				icon: 'none',
				duration: 2000
			})
			return false;
		};
		if (that.data.password_text == '') {
			wx.showToast({
				title: '请输入密码！',
				icon: 'none',
				duration: 2000
			})
			return false;
		};
		return true;
	},
	ap_submint() {
		let that = this;
		let ok_fill = that.is_fill();
		if (!ok_fill) {
			return false;
		}
		that.login().then(() => {
			let user_name = that.data.account_text;
			let password = that.data.password_text;
			let openid = that.data.openid;
			return new Promise(function (resolve, vpay) {
				return request(LoginWxByAccount, {username: user_name, password: password, openid: openid }, 'POST').then(res => {
					if (res.code === 1) {
						wx.showToast({
							title: '登录成功！',
							icon: 'success',
							duration: 2000
						})
						let userInfo = res.data.userInfo;
						let token = res.data.token;
						wx.setStorageSync('userInfo', userInfo);
						wx.setStorageSync('token', token);
              wx.switchTab({
                url: '/pages/index/index/index'
              });
					}else{
						wx.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000//持续的时间
						})
					}
					// resolve(res);
				}).catch((err) => {
					vpay(err);
				});
			}).catch(function () {
			});
		});
	}
})